package com.example.pay_service.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import javax.servlet.http.HttpServletResponse;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.example.pay_service.config.AlipayConfig;

import com.example.pay_service.otherservice.ActivityService;
import com.example.pay_service.otherservice.OrderService;
import com.example.pay_service.otherservice.UserService;
import com.example.pay_service.return_data.Mall_Data;
import com.example.pay_service.service.ShoppingService;
import com.example.pay_service.vo.Mingxi;
import com.example.pay_service.vo.Order;
import com.example.pay_service.vo.Orders;
import com.example.pay_service.vo.Red;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import io.swagger.annotations.Api;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/pay")
@Api
public class PayController {


    @Autowired
    ShoppingService shoppingService;
//
//    @Autowired
//    User_Service user_service;//远程调用用户服务接口

    @Autowired
    ActivityService activity_service;//远程调用优惠劵接口

    @Autowired
    UserService userService;

    @Autowired
    OrderService orderService;


    private int shu = 1;
    private List<String> list = new ArrayList();//保存订单号
    private List<Integer> list2 = new ArrayList();//保存购物车ID
    private static Map map = new  HashMap();
    private int coupon ;
    private int user_id;
    private String jifen;
    private Mingxi mingxi = new Mingxi();

    @RequestMapping("/pay")
    public void getpay(Order order,HttpServletResponse response) throws AlipayApiException, IOException, WriterException {
        if (order.getPay()==1){
            scan_code(order,response);
        }else if (order.getPay()==2){
            pay(order,response);
        }
    }

    public static BitMatrix createCode(String content) throws IOException {
        //二维码的宽高
        int width = 350;
        int height = 350;

        //其他参数，如字符集编码
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        //容错级别为H
        hints.put(EncodeHintType.ERROR_CORRECTION , ErrorCorrectionLevel.H);
        //白边的宽度，可取0~4
        hints.put(EncodeHintType.MARGIN , 0);

        BitMatrix bitMatrix = null;
        try {
            //生成矩阵，因为我的业务场景传来的是编码之后的URL，所以先解码
            bitMatrix = new MultiFormatWriter().encode(content,
                    BarcodeFormat.QR_CODE, width, height, hints);

            //bitMatrix = deleteWhite(bitMatrix);
        } catch (WriterException e) {
            e.printStackTrace();
        }

        return bitMatrix;
    }

    /**
     *  删除生成的二维码周围的白边，根据审美决定是否删除
     * @param matrix BitMatrix对象
     * @return BitMatrix对象
     * */
    private static BitMatrix deleteWhite(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1]))
                    resMatrix.set(i, j);
            }
        }
        return resMatrix;
    }


    public void scan_code(Order order,HttpServletResponse responses) throws AlipayApiException, IOException, WriterException {
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL,AlipayConfig.APPID,AlipayConfig.RSA_PRIVATE_KEY,AlipayConfig.FORMAT, AlipayConfig.CHARSET,AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setNotifyUrl(AlipayConfig.notify_url);
        //request.setReturnUrl("https://www.baidu.com");
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", order.getOrderId());
        bizContent.put("total_amount", order.getShopPrice());
        bizContent.put("subject", order.getOrderDesc());

        request.setBizContent(bizContent.toString());
        AlipayTradePrecreateResponse response = alipayClient.execute(request);

        System.out.println(response.getBody());
        System.out.println(response.getOutTradeNo());
        System.out.println(response.getQrCode());

        OutputStream stream = responses.getOutputStream();
        BitMatrix bitMatrix =createCode(response.getQrCode());
        //以流的形式输出到前端
        MatrixToImageWriter.writeToStream(bitMatrix , "jpg" , stream);


        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }

        if (response.getCode()=="1000"){
            responses.sendRedirect("https://www.baidu.com");
        }else {
            responses.sendRedirect("https://www.baidu.com");
        }

    }


    public void pay(Order order,HttpServletResponse response) {
        // 商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = order.getOrderId();
        System.out.println(out_trade_no);
        // 订单名称，必填
        String subject = order.getShopName();
        System.out.println(subject);
        // 付款金额，必填
        String total_amount=order.getShopPrice()+"";
        System.out.println(total_amount);
        // 商品描述，可空
        String body = order.getOrderDesc();
        System.out.println(body);
        // 超时时间 可空
        String timeout_express="2m";
        // 销售产品码 必填
        String product_code="QUICK_WAP_WAY";
        /**********************/

        Calendar calendar=Calendar.getInstance();//获得当前时间的月份，月份从0开始所以结果要加1
        int month=calendar.get(Calendar.MONTH)+1;
        long t=new Date().getTime();//获取当前时间戳
        String ordernumber=month+""+t; //订单编号 月份+用户id+时间戳
        Orders orders = new Orders();
        orders.setOrderid(ordernumber);
        orders.setUserid(1);

        //System.out.println("这是优惠劵id哦"+order.getCoupon());

        coupon=order.getCoupon();
        // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
        //调用RSA签名方式
        AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
        AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest();

        // 封装请求支付信息
        AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
        model.setOutTradeNo(out_trade_no);
        model.setSubject(subject);
        model.setTotalAmount(total_amount);
        model.setBody(body);
        model.setTimeoutExpress(timeout_express);
        model.setProductCode(product_code);
        alipay_request.setBizModel(model);
        // 设置异步通知地址
        alipay_request.setNotifyUrl(AlipayConfig.notify_url);
        // 设置同步地址
        alipay_request.setReturnUrl(AlipayConfig.return_url);

        // form表单生产
        String form = "";
        try {
//            // 调用SDK生成表单
            form = client.pageExecute(alipay_request).getBody();
            response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
            response.getWriter().write(form);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
      } catch (AlipayApiException | IOException e) {
          // TODO Auto-generated catch block
           e.printStackTrace();
        }

    }

    @RequestMapping("/notify_url")
    public void notify_url(){

        System.out.println("这是优惠劵id哦"+coupon);
        System.out.println("这是用户id哦"+user_id);
        System.out.println("支付宝异步通知"+111111);


//        System.out.println(jifen);
//        System.out.println(mingxi.getCommodity_name()+"=="+mingxi.getCommodity_picture()+"=="+mingxi.getAttribute());


            activity_service.updatezt(coupon,2);//修改优惠劵状态为已使用
            userService.update_member_existing_integral(user_id, "+" + jifen, mingxi);//新增积分和积分日志




        for (int i = 0; i < list.size(); i++) {
            System.out.println("这是要修改的订单"+list.get(i));
            orderService.updatedd(list.get(i));
        }
        if (list2.size()>0)
        for (int i = 0; i < list2.size(); i++) {
            System.out.println("这是要删除的购物车"+list2.get(i));
            shoppingService.delshopping(list2.get(i));

        }

        System.out.println("这是修改"+map.get("状态"));
        if (map.get("状态")!=null){
            if (map.get("状态").equals("结束")){
                System.out.println("清空");
                list=new ArrayList();
                list2=new ArrayList();
            }
        }

    }

//    @RequestMapping("/return_url")
//    public String return_url(){
//
//    }

//    //完成支付，写入数据库
//    @RequestMapping("/complete")
//    public void complete(HttpServletRequest request, HttpServletResponse response) {
//
//        //从session中获取定点信息
//        Order order=(Order)request.getSession().getAttribute("order");
//        System.out.println(order);
//        try {
//            //将数据插入到订单表中
//            payService.insertOrder(order);
//            response.sendRedirect(request.getContextPath()+"/payDemo.html");
//        } catch (Exception e) {
//            // TODO: handle exception
//            e.printStackTrace();
//        }
//
//    }

    @RequestMapping("/addorder")
    public void addorder(Orders orders){
        System.out.println(orders.getUserid());
        System.out.println("这是状态"+orders.getState());
        System.out.println("这是购物车ID"+orders.getCart_id());
       // if (orders.getState().equals("结束")){
            map.put("状态",orders.getState());
       // }

        System.out.println(orders.getJifen());

        list.add(orders.getOrdernumber());
        list2.add(orders.getCart_id());
        System.out.println("这是生成的订单"+orders.getOrdernumber());
        System.out.println(orders.getCommodity_name());
        user_id=orders.getUserid();
        jifen=orders.getJifen();

        mingxi.setUserid(orders.getUserid());
        mingxi.setCommodity_name(orders.getCommodity_name());
        mingxi.setCommodity_picture(orders.getComitypicture());
        mingxi.setAttribute(orders.getSpecifications());
        mingxi.setJifen(orders.getJifen());


        System.out.println("这是商品ID"+orders.getSpid());
        System.out.println(orders.getPayway());
        System.out.println(orders.getLogisticscompany());
        System.out.println(orders.getOrderstatus());
        System.out.println(orders.getComitydescription());
        System.out.println(orders.getComityprices());
        System.out.println(orders.getComitynumber());
        System.out.println(orders.getComitypicture());
        System.out.println(orders.getSettlementprice());
        System.out.println(orders.getAddressid());
        System.out.println(orders.getFreight());
        System.out.println(orders.getActualpayment());
        System.out.println(orders.getPreferentialinformation());
        System.out.println(orders.getSpecifications());

        if (orders.getPayway().equals("")) {
            orderService.insertorder(orders.getAddressid(), orders.getUserid(), orders.getSpid(), orders.getOrdernumber(), "", orders.getComitydescription(),
                    orders.getComityprices(), orders.getComitynumber(), orders.getComitypicture(), orders.getSettlementprice(),
                    orders.getFreight(), orders.getActualpayment(), orders.getPreferentialinformation(), orders.getSpecifications()
            );
        }


    }

    @RequestMapping("/showhb")
    public Mall_Data selyhj(@RequestParam("user_id") int user_id){
        List<Red> list = activity_service.searchhb(user_id);
        Mall_Data mall_data = new Mall_Data();
        if (list.size()>0){
            mall_data.setcode(200);
            mall_data.seterror("查询优惠劵成功");
            mall_data.setdata(list);
            return mall_data;
        }
        mall_data.setcode(500);
        mall_data.seterror("查询优惠劵失败");
        mall_data.setdata("");
        return mall_data;

    }


}

